package reservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import controller.Domain;
import controller.ReDomain;
import controller.Utils;



public class Whois extends Thread{
	ReDomain domain;
	public Whois(ReDomain domain)
	{
		this.domain=domain;
		this.start();
	}
	
	public void run()
	{
		try {
			Process process;
			BufferedReader buf;
			String line;
			String whois="";
			if(!Utils.checkSubDomain(domain.getName()))
			{
	        	process = Runtime.getRuntime().exec("whois "+domain.getName());
				buf = new BufferedReader(new InputStreamReader(
				process.getInputStream()));

				while ((line = buf.readLine()) != null) {
					whois += line+"<br/>";
				}
			} else {
				process = Runtime.getRuntime().exec("whois "+Utils.returnSubDomainTo(domain.getName()));
				buf = new BufferedReader(new InputStreamReader(
				process.getInputStream()));

				while ((line = buf.readLine()) != null) {
					whois += line+"<br/>";
				}
			}
			
			
			String ip = "";
			try {
				InetAddress giriAddress = java.net.InetAddress.getByName(domain.getName());
				ip = giriAddress.getHostAddress();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			Pattern p = Pattern.compile("[^ :]+@[^ ]+");

	        Matcher m = p.matcher(whois.replaceAll("\\<.*?\\>", " "));

	        ArrayList<String> email = new ArrayList<String>();
	        String listEmail = "";
	        while (m.find()) {
	        	int k=0;
	        	for (int i = 0; i < email.size(); i++) {
					if(email.get(i).equals(m.group().replaceAll("[()]+", "")))
					{
						k=1;
					}
				}
	        	if(k==0)
	        	{
	        		email.add(m.group().replaceAll("[()]+", ""));
	        		listEmail += m.group().replaceAll("[()]+", "")+" , ";
	        	}
	        }
			domain.setEmail(listEmail);
			domain.setWhois(whois);

			domain.setIp(ip);
        

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

	}
//	public static void main( String args[])
//	{
//		new Whois("ketoan.org");
//	}
}
